<?php

declare(strict_types=1);

namespace app\api\controller\customer;

use app\api\controller\Api;
use util\Format;

class Cost extends Api {
    
    public function index() {
        $post = $this->request->post();

        list($cfg) = Format::pagination($post);
        $where = [];
        if (!empty($post['source_id'])) {
            $where[] = ['source_id', '=', $post['source_id']];
        }

        if (!empty($post['range'])) {
            $range = Format::dateRange($post['range']);
            $where[] = ['cost_date', 'between', $range];
        }

        $model = new \app\common\customer\model\OperateCost();
        $pg = $model->where($where)->order('id desc')->paginate($cfg);

        $rows = $pg->getCollection();
        foreach ($rows as $row) {
            $row->append(['user', 'brand', 'source']);
        }


        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    // 创建
    public function create() {
        $post = $this->request->post();
        $validate = new \app\common\customer\validate\OperateCostValidate();
        if (!$validate->scene('create')->check($post)) {
            return error([], $validate->getError());
        }

        $model = new \app\common\customer\model\OperateCost();
        $user = $this->request->user;
        $post['user_id'] = $user['id'];
        $model->save($post);

        return success($model, '创建成功');
    }

    // 更新
    public function update() {
        $post = $this->request->post();
        $validate = new \app\common\customer\validate\OperateCostValidate();
        if (!$validate->scene('update')->check($post)) {
            return error([], $validate->getError());
        }

        $model = new \app\common\customer\model\OperateCost();
        $user = $this->request->user;
        $post['user_id'] = $user['id'];
        $row = $model->find($post['id']);
        if (empty($row)) {
            return error([], '数据不存在');
        }

        
        $row->save($post);

        return success($model, '更新成功');
    }

    // 删除
    public function delete() {
        $post = $this->request->post();
        $validate = new \app\common\customer\validate\OperateCostValidate();
        if (!$validate->scene('delete')->check($post)) {
            return error([], $validate->getError());
        }

        $model = new \app\common\customer\model\OperateCost();
        $row = $model->find($post['id']);
        if (empty($row)) {
            return error([], '数据不存在');
        }

        $row->delete();

        return success([], '删除成功');
    }
}